// include requirements
include(jslib_fileutils);

// on load populate scripts
function eventLoad() {
	var scriptsListBox = document.getElementById('scriptsListBox');
	var stringBundle = document.getElementById('stringBundle');

	helper_populateScripts(scriptsListBox, stringBundle);
}

// on unload remove mem leaks
function eventUnload() {
	window.removeEventListener('load', eventLoad, false);
	window.removeEventListener('unload', eventUnload, false);
}

// detects changes in the scripts and update the list
function detectScriptChange() {
	var stringBundle = document.getElementById('stringBundle');
	var changeDetected = false;

	var fu = new FileUtils;
	var scripts = TH_getInfo('scripts');

	for (var i = 0; i < scripts.length; i++) {
		var modified = fu.dateModified(scripts[i].path);
		
		if (modified != scripts[i].modified) {
			changeDetected = true;

			try {
				TH_updateScript(scripts[i], TH_parseScript(scripts[i].source));
			} catch (e) {
				if (e == 'incorrect format')
					if (confirm(scripts[i].name + ' ' + stringBundle.getString('part_incorrectScriptFormatConfirm')))
						TH_removeScript(scripts[i]);
					else {
						TH_removeScriptSafe(scripts[i]);
						alert(stringBundle.getString('incorrectScriptFormatRemove'));
					}
				else if (e == 'script exists')
					alert(scripts[i].name + ' ' + stringBundle.getString('part_scriptExists') + ' ' + stringBundle.getString('incorrectScriptFormatAlertMessage'));
				else
					alert(scripts[i].name + ' ' + stringBundle.getString('part_scriptCannotBeInstalled') + ' ' + stringBundle.getString('incorrectScriptFormatAlertMessage'));
			}
		}
	}

	if (changeDetected) {
		var scriptsListBox = document.getElementById('scriptsListBox');
		var stringBundle = document.getElementById('stringBundle');

		helper_populateScripts(scriptsListBox, stringBundle);
	}	
}

// set events for load and unload
window.addEventListener('load', eventLoad, false);
window.addEventListener('unload', eventUnload, false);

// set the script change detection function
window.setInterval(detectScriptChange, 5000);